<template>
  <!-- 《课堂表现》 -->
  <div class="tables">
    <!-- 搜索项 -->
    <div class="search_bar flexBet">
      <div class="greenText">
        班级平均分 : {{ resclass.avgScore ? resclass.avgScore.toFixed(2) : 0 }}
      </div>

      <div class="inputs flex">
        <div class="label">学生</div>
        <el-input
          style="width: 180px"
          class="inputstyle"
          v-model="queryParams.search"
          placeholder="请输入学生姓名/学号"
          clearable
          @keyup.enter.native="queryParamsSearch"
          @clear="queryParamsSearch"
        />
        <div class="label" style="margin-left: 24px">分数范围</div>
        <el-input
          oninput="value=value.replace(/[^0-9]|^0+(?!$)/g,'');"
          style="width: 90px"
          class="inputstyle"
          v-model="queryParams.minScore"
          placeholder="请输入"
          clearable
          @keyup.enter.native="queryParamsSearch"
          @clear="queryParamsSearch"
        />
        <div style="margin: 0 10px">-</div>
        <el-input
          oninput="value=value.replace(/[^0-9]|^0+(?!$)/g,'');"
          style="width: 90px"
          class="inputstyle"
          v-model="queryParams.maxScore"
          placeholder="请输入"
          clearable
          @keyup.enter.native="queryParamsSearch"
          @clear="queryParamsSearch"
        />
        <div
          class="primaryBorderBtn w88"
          style="margin-left: 24px"
          @click="queryParamsSearch"
        >
          搜索
        </div>

        <div
          class="normalBtn w88"
          @click="resetQueryParamsSearch"
          style="margin-left: 12px"
        >
          重置
        </div>
      </div>
    </div>

    <div
      class="data_table"
      style="margin-top: 16px; height: calc(100vh - 330px)"
    >
      <!-- 问卷列表 -->
      <el-table border v-loading="loading" :data="list" height="100%">
        <el-table-column
          show-overflow-tooltip
          label="学生（学号）"
          align="center"
          prop="studentName"
        >
          <template slot-scope="scope">
            {{ scope.row.studentName }}({{ scope.row.studentNum }})
          </template>
        </el-table-column>
        <el-table-column
          show-overflow-tooltip
          sortable
          :label="
            usualType == 1 ? '课堂表现分' : usualType == 3 ? '纪律分' : '其他分'
          "
          align="center"
          prop="normalScore"
        >
          <template slot-scope="scope">
            {{ scope.row.normalScore }}
          </template>
        </el-table-column>
        <!-- 操作列 -->
        <el-table-column
          show-overflow-tooltip
          label="操作"
          align="center"
          prop="branchName"
        >
          <template slot-scope="scope">
            <el-button
              type="text"
              size="mini"
              @click="handleDetail(scope.row, scope.$index)"
            >详情
            </el-button
            >
            <el-button
              type="text"
              size="mini"
              @click="handleAdd(scope.row, scope.$index, 'index')"
            >新增
            </el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 详情抽屉 -->
    <el-drawer
      :with-header="false"
      :title="usualType == 1 ? '课堂表现' : usualType == 3 ? '纪律' : '其他'"
      :visible.sync="showDrawer"
      size="700px"
      direction="rtl"
      :before-close="drawer_handleClose"
    >
      <div class="drawer-title">
        {{ usualType == 1 ? '课堂表现' : usualType == 3 ? '纪律' : '其他' }}
      </div>
      <div class="drawer-content">
        <div class="flexBet drawer-cards">
          <!-- 学生信息 -->
          <div class="drawer-card">
            <div class="drawer-card-title flex">
              <div></div>
              学生信息
            </div>
            <div class="drawer-studentInfo-contian">
              <div class="drawer-studentInfo-contian-item flex">
                <span>学&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;生：</span
                >{{ row.studentName }}({{ row.studentNum }})
              </div>
              <div class="drawer-studentInfo-contian-item flex">
                <span>授课班级：</span>{{ schedulingName }}
              </div>
              <div class="drawer-studentInfo-contian-item flex">
                <span>课&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;程：</span
                >{{ row.courseName }}
              </div>
            </div>
          </div>

          <!-- 得分 -->
          <div class="drawer-card">
            <div class="drawer-card-title flex">
              <div></div>
              得分
            </div>
            <div class="drawer-score">
              {{
                usualType == 1
                  ? data.usualScore
                  : usualType == 3
                    ? data.disciplineScore
                    : data.otherScore
              }}
            </div>
          </div>
        </div>

        <div class="flex drawer-chart rela">
          <div style="" class="chart" ref="chart"></div>
          <div class="chartsTip absolute">
            <el-radio-group
              size="small"
              v-model="drawer_dataType"
              @input="drawer_radioGroupChange"
              style="margin-bottom: 30px"
            >
              <el-radio-button label="1">日</el-radio-button>
              <el-radio-button label="2">周</el-radio-button>
              <el-radio-button label="3">月</el-radio-button>
            </el-radio-group>
          </div>
        </div>
        <div class="drawer-table">
          <!-- 新增按钮 -->
          <div class="search_bar">
            <div class="primaryBtn w86" @click="drawer_handleAdd()">
              <svg-icon class-name="icon-img" icon-class="add_svg"/>
              新增
            </div>
          </div>
          <div class="data_table">
            <el-table
              border
              v-loading="loading"
              :data="drawer_scoreRecordList"
              height="calc(100vh - 220px)"
            >
              <el-table-column
                show-overflow-tooltip
                label="打分"
                align="center"
                prop="score"
              >
                <template slot-scope="scope">
                  {{
                    scope.row.score < 0 || scope.row.score == 0
                      ? scope.row.score
                      : '+' + scope.row.score
                  }}
                </template>
              </el-table-column>
              <el-table-column
                show-overflow-tooltip
                label="打分教师"
                align="center"
                prop="teacherName"
              >
              </el-table-column>
              <el-table-column
                show-overflow-tooltip
                sortable
                label="打分时间"
                align="center"
                prop="operateTime"
              >
                <template slot-scope="scope">
                  {{ parseTime(scope.row.operateTime) }}
                </template>
              </el-table-column>
              <el-table-column
                show-overflow-tooltip
                label="打分备注"
                align="center"
                prop="remark"
              >
                <template slot-scope="scope">
                  {{ scope.row.remark ? scope.row.remark : '--' }}
                </template>
              </el-table-column>
              <!-- 操作列 -->
              <el-table-column
                show-overflow-tooltip
                label="操作"
                align="center"
              >
                <template slot-scope="scope">
                  <el-button
                    type="text"
                    size="mini"
                    @click="drawer_handleEdit(scope.row)"
                  >编辑
                  </el-button
                  >
                  <el-button
                    type="text"
                    size="mini"
                    @click="drawer_handleDel(scope.row, 'index')"
                  >删除
                  </el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </div>
      <div class="search_bar flexEnd" style="padding: 10px 20px 0 0">
        <div class="normalBtn w88" @click="drawer_handleClose()">关 闭</div>
      </div>
    </el-drawer>
    <!-- 新增弹窗 -->
    <el-dialog
      :title="
        usualType == 1
          ? '课堂表现打分'
          : usualType == 3
          ? '纪律打分'
          : '其他打分'
      "
      :visible.sync="open"
      width="600px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      append-to-body
      @close="cancel()"
    >
      <el-form
        @submit.native.prevent
        ref="form"
        :model="form"
        :rules="rules"
        label-width="120px"
      >
        <el-form-item label="课程名：" prop="teacherNum">
          {{ form.courseName }}
        </el-form-item>
        <el-form-item label="学生：" prop="name">
          {{ form.studentName }}({{ form.studentNum }})
        </el-form-item>

        <el-form-item
          :label="
            usualType == 1
              ? '课堂表现打分:'
              : usualType == 3
              ? '纪律打分:'
              : '其他打分:'
          "
          prop="sex"
        >
          {{ form.normalScore }}
        </el-form-item>
        <el-form-item label="本次打分：" prop="score">
          <div class="flexColCenter">
            <el-radio-group
              size="small"
              v-model="scoreType"
              @input="scoreTypeChange"
            >
              <el-radio-button label="add">加</el-radio-button>
              <el-radio-button label="subtract">减</el-radio-button>
            </el-radio-group>
            <el-input-number
              :precision="1"
              v-model="form.score"
              controls-position="right"
              :min="0"
              :step="0.1"
            ></el-input-number>
            分 <span>（精确到十分位）</span>
          </div>
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            type="textarea"
            :autosize="{ minRows: 2, maxRows: 4 }"
            v-model="form.remark"
            placeholder="请输入备注"
            clearable
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button v-preventReClick @click="cancel">取 消</el-button>
        <el-button
          v-preventReClick
          type="primary"
          v-if="rowIndex > 0 && openType == 'index'"
          @click="previous"
        >
          上一份
        </el-button>
        <el-button
          v-preventReClick
          type="primary"
          v-if="rowIndex < this.list.length - 1 && openType == 'index'"
          @click="next"
        >
          下一份
        </el-button>
        <el-button v-preventReClick type="primary" @click="submitForm">
          打 分
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { getCourseSchedulingInfo } from '@/api/teach/teach'
import {
  usualScorelineChart,
  classNormal,
  listusuallyPoints,
  addusuallyPoints,
  updateusuallyPoints,
  detailusuallyPoints,
  delusuallyPoints
} from '@/api/tea_studentGrade/usual'
import * as echarts from 'echarts'
import { formatDate } from '@/utils'

export default {
  props: {
    activeName: {
      type: String
    }
  },
  data() {
    return {
      usualType: 1,
      list: [],
      data: {},
      loading: false,
      // 总条数
      total: 3,
      // 搜索条件
      queryParams: {
        type: 1,
        pageNum: 1,
        pageSize: 10,
        search: '',
        maxScore: '',
        minScore: ''
      },

      // 表单参数
      row: {},
      //   用于上一份下一份
      rowIndex: 0,
      showDrawer: false,
      drawer_scoreRecordList: [],
      //用于抽屉的周月日
      drawer_dataType: 1,
      //用于抽屉 打分记录的编辑数据带入
      drawer_row: {},
      open: false,
      // 用于是首页新增index 还是 抽题详情-新增编辑detailAdd detailUpdate 来判定操作实现后续逻辑
      openType: 'index',
      scoreType: 'add',
      form: {
        type: 1,
        remark: '',
        score: 0
      },
      // 表单校验
      rules: {
        score: [
          { required: true, message: '分数不能为空', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              if (value === 0 || value === '0') {
                callback(new Error('分数不能为0'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ]
      },
      resclass: '',
      schedulingName: ''
    }
  },
  watch: {
    activeName: {
      handler(newValue) {
        if (newValue == 'normal_other') {
          this.schedulingName = JSON.parse(
            localStorage.getItem('COURSE_INFO')
          ).schedulingName
          this.usualType = 4
          this.queryParams.type = this.usualType
          this.form.type = this.usualType
          this.getList()
        }
      },
      immediate: true // 这个选项确保handler在watcher被创建时立即调用
    }
  },
  mounted() {
  },
  methods: {
    // 抽屉-图标 周月日
    drawer_radioGroupChange(e) {
      console.log(e)
      this.setOptionCdn()
    },
    scoreTypeChange(e) {
    },
    // 抽屉-打分编辑
    drawer_handleEdit(row) {
      this.drawer_row = {
        ...row,
        ...this.row,
        type: this.usualType,
        remark: row.remark ? row.remark : ''
      }
      this.scoreType = this.drawer_row.score > 0 ? 'add' : 'subtract'
      this.form = JSON.parse(JSON.stringify(this.drawer_row))
      this.form.normalScore = this.data.usualScore
      this.form.score = Math.abs(this.form.score)
      console.log('form', this.form)
      this.openType = 'detailUpdate'
      this.open = true
    },
    // 抽屉-记录删除
    drawer_handleDel(row) {
      this.$confirm('删除后，本操作不可撤销，是否确认删除？', '删除确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          let res = await delusuallyPoints(row.id)
          const { code } = res
          if (code == 200) {
            this.$modal.msgSuccess('删除成功!')
            this.getDrawerList()
            this.setOptionCdn()
          }
        })
        .catch(() => {
        })
    },
    // 抽屉-关闭
    drawer_handleClose() {
      this.showDrawer = false
    },
    // 抽屉- 新增记录按钮
    drawer_handleAdd() {
      this.form = JSON.parse(JSON.stringify({ ...this.row, ...this.form }))
      this.form.normalScore = this.data.otherScore
      console.log('form', this.form)
      this.openType = 'detailAdd'
      this.open = true
    },
    // 详情打开-抽屉
    async handleDetail(row, index) {
      this.rowIndex = index
      this.row = { ...row, ...JSON.parse(localStorage.getItem('COURSE_INFO')) }
      this.showDrawer = true
      //   渲染图标
      this.$nextTick(() => {
        this.setOptionCdn()
      })
      //   加载表格
      this.getDrawerList()
    },
    // 新增打分
    handleAdd(row, index) {
      this.rowIndex = index
      this.row = { ...row, ...JSON.parse(localStorage.getItem('COURSE_INFO')) }
      this.form = JSON.parse(JSON.stringify({ ...this.row, ...this.form }))
      this.openType = 'index'
      this.open = true
      this.reset()
    },
    // 上一份
    async previous() {
      await this.submitForm('prev')
      this.rowIndex--
      this.row = {
        ...this.list[this.rowIndex],
        ...JSON.parse(localStorage.getItem('COURSE_INFO'))
      }
      // 重置表单
      this.reset()
    },
    // 下一份
    async next() {
      await this.submitForm('next')
      this.rowIndex++
      this.row = {
        ...this.list[this.rowIndex],
        ...JSON.parse(localStorage.getItem('COURSE_INFO'))
      }
      // 重置表单
      this.reset()
    },
    // 抽屉-获取打分记录
    async getDrawerList() {
      this.loading = true
      try {
        let res = await detailusuallyPoints(this.row.courseStuId, {
          type: this.usualType
        })
        const { code, data } = res
        if (code == 200) {
          this.data = data
          this.drawer_scoreRecordList = data.list
        }
      } catch (error) {
        console.error(error)
      } finally {
        this.loading = false
      }
    },
    // 搜索按钮
    queryParamsSearch() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    // 检索表单重置
    resetQueryParamsSearch() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        type: this.usualType,
        search: '',
        maxScore: '',
        minScore: ''
      }
      this.queryParamsSearch()
    },

    async getList() {
      this.loading = true
      try {
        let resclass = await classNormal(
          JSON.parse(localStorage.getItem('COURSE_INFO')).courseSchedulingId,
          this.queryParams
        )
        this.resclass = resclass.data
        let res = await listusuallyPoints(
          JSON.parse(localStorage.getItem('COURSE_INFO')).courseSchedulingId,
          this.queryParams
        )
        const { code, rows, total } = res
        if (code == 200) {
          this.total = total
          this.list = rows
        }
      } catch (error) {
        console.error(error)
      } finally {
        this.loading = false
      }
    },
    // 导出
    async confirmexport(str) {
      let obj = this.queryParams
      obj.params = str
      this.download(
        `/school/system/exportData/courseConstructionExport`,
        obj,
        `课程建设情况表_${formatDate(new Date())}.xlsx`
      )
    },

    // 新增打分表 关闭按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 新增打分表单 重置
    reset() {
      this.scoreType = 'add'
      this.form = {
        ...this.row,
        type: this.usualType,
        remark: '',
        score: 0
      }
      this.resetForm('form')
    },
    /** 新增打分表单提交按钮 */
    submitForm: function(type) {
      this.$refs['form'].validate(async(valid) => {
        if (valid) {
          this.loading = true
          try {
            let data = JSON.parse(JSON.stringify(this.form))
            data.score = this.scoreType == 'add' ? data.score : -data.score
            data.teacherId = this.$store.getters.teacherId
            let res
            if (this.openType == 'detailUpdate') {
              res = await updateusuallyPoints(data)
            } else {
              res = await addusuallyPoints(data)
            }
            const { code } = res
            if (code == 200) {
              this.$modal.msgSuccess('打分成功!')
              this.getList()
              // 上一份下一份
              if (type == 'next' || type == 'prev') {
              } else {
                this.open = false
                // 如果是首页,则刷新首页
                if (this.openType == 'index') {
                }
                // 如果是抽屉新增
                else {
                  this.getDrawerList()
                  this.setOptionCdn()
                }
              }
            }
          } catch (error) {
            console.error(error)
          } finally {
            this.loading = false
          }
        }
      })
    },
    // 抽屉-图表生成
    async setOptionCdn() {
      try {
        // 获取初始分
        let scoreRes = await getCourseSchedulingInfo(
          JSON.parse(localStorage.getItem('COURSE_INFO')).courseSchedulingId
        )
        let res = await usualScorelineChart(
          {
            type: 4,
            courseSchedulingId: JSON.parse(localStorage.getItem('COURSE_INFO'))
              .courseSchedulingId,
            dateType: this.drawer_dataType
          },
          this.row.courseStuId
        )
        if (res.code == 200 && scoreRes.code == 200) {
          // 初始分
          let initScores = []
          res.data.classScorelineChart.map(() => {
            initScores.push(scoreRes.data.initialOtherScore)
          })
          let myChart = echarts.init(this.$refs.chart)
          let option
          option = {
            tooltip: {
              trigger: 'axis',
              axisPointer: {
                type: 'cross',
                label: {
                  backgroundColor: '#6a7985'
                }
              }
            },
            legend: {
              icon: 'path://M10,20 a 10,10 0 0 1 10,-10 h 30 a 10,10 0 0 1 10,10 v 30 a 10,10 0 0 1 -10,10 h -30 a 10,10 0 0 1 -10,-10 z',
              itemWidth: 14, // 正方形宽度
              itemHeight: 14, // 正方形高度,
              data: ['班级平均分', '我的得分', '初始分']
            },
            toolbox: {
              feature: {
                saveAsImage: {}
              }
            },
            grid: {
              left: '3%',
              right: '0%',
              bottom: '3%',
              containLabel: true
            },
            xAxis: [
              {
                type: 'category',
                data: res.data.classScorelineChart.map((item) => {
                  if (this.drawer_dataType == 1 || this.drawer_dataType == 2) {
                    return item.date.slice(5, item.date.length)
                  } else {
                    return item.date.slice(0, item.date.length - 3)
                  }
                }),
                axisTick: {
                  alignWithLabel: true
                },
                axisLabel: {
                  interval: 0
                }
              }
            ],
            yAxis: [
              {
                type: 'value'
              }
            ],
            series: [
              {
                name: '班级平均分',
                type: 'line',
                data: res.data.classScorelineChart.map((item) => {
                  return item.score
                }),
                smooth: true,
                lineStyle: {
                  color: '#62FBFF '
                },
                itemStyle: {
                  color: '#62FBFF ' // 图例项颜色，使用渐变的起始颜色
                }
              },
              {
                name: '我的得分',
                type: 'line',

                data: res.data.stuScorelineChart.map((item) => {
                  return item.score
                }),
                smooth: true,
                lineStyle: {
                  color: '#E92B97'
                },
                itemStyle: {
                  color: '#E92B97 ' // 图例项颜色，使用渐变的起始颜色
                }
              },
              {
                name: '初始分',
                type: 'line',
                data: initScores,
                smooth: true,
                lineStyle: {
                  color: '#4C71E4'
                },
                itemStyle: {
                  color: '#4C71E4 ' // 图例项颜色，使用渐变的起始颜色
                }
              }
            ]
          }
          option && myChart.setOption(option)
        }
      } finally {
      }
    }
  }
}
</script>
<style scoped lang="scss">
.w88 {
  width: 88px;
}

.w124 {
  width: 124px;
}

.drawer-table {
  margin-top: 44px;

  .data_table {
    margin-top: 16px;
  }
}

.drawer-chart {
  margin-left: 25px;
  margin-top: 38px;
  width: 597px;
  height: 218px;

  .chart {
    width: 597px;
    height: 218px;
  }

  .chartsTip {
    top: -4px;
    right: 0;
  }
}

.drawer-title {
  box-sizing: border-box;
  height: 70px;
  border-bottom: 1px solid #edeff0;
  padding-left: 32px;
  font-family: PingFangSC, PingFang SC, sans-serif;
  font-weight: 600;
  font-size: 18px;
  color: #333333;
  line-height: 70px;
  text-align: left;
  font-style: normal;
}

.drawer-content {
  height: calc(100vh - 140px);
  overflow-y: auto;
  padding: 16px 20px 0 24px;

  .drawer-cards {
    .drawer-card {
      width: 320px;
      height: 190px;
      background-image: url("../../../assets/images/scoreBg.png");
      background-size: 320px 190px;
      border-radius: 8px;
      box-sizing: border-box;

      .drawer-card-title {
        padding: 15px 0 0 8px;
        font-family: PingFangSC, PingFang SC, sans-serif;
        font-weight: 400;
        font-size: 16px;
        color: #333333;
        line-height: 20px;
        text-align: left;
        font-style: normal;

        div {
          margin-right: 10px;
          width: 6px;
          height: 20px;
          background: #28b28b;
          border-radius: 1px;
        }
      }

      .drawer-studentInfo-contian {
        margin: 20px 0 0 25px;

        .drawer-studentInfo-contian-item {
          margin-bottom: 16px;
          font-family: PingFangSC, PingFang SC, sans-serif;
          font-weight: 400;
          font-size: 16px;
          color: #333333;
          line-height: 22px;
          font-style: normal;

          span {
            font-family: PingFangSC, PingFang SC, sans-serif;
            font-weight: 400;
            font-size: 16px;
            color: #788295;
            line-height: 22px;
            font-style: normal;
          }
        }
      }

      .drawer-score {
        padding: 20px 0 0 0;
        text-align: center;
        font-family: PingFangSC, PingFang SC, sans-serif;
        font-weight: 500;
        font-size: 72px;
        color: #28b28b;
        line-height: 100px;
        font-style: normal;
      }
    }
  }
}

.greenText {
  font-family: PingFangSC, PingFang SC, sans-serif;
  font-weight: 500;
  font-size: 14px;
  color: #28b28b;
  text-align: left;
  font-style: normal;
}

.tables {
  padding: 16px 24px;
  width: 100%;
}

.exportbtn {
  display: flex;
  justify-content: space-between;

  margin: 10px 0;
}

::v-deep .el-table__body-wrapper::-webkit-scrollbar {
  -webkit-appearance: none;
  background-color: #fff;
  /* 滚动条背景颜色 */
  height: 8px;
  /* 滚动条高度 */
}

::v-deep .el-table__body-wrapper::-webkit-scrollbar-thumb {
  border-radius: 4px;
  background-color: #bfbfbf;
}

::v-deep .el-table__body-wrapper::-webkit-scrollbar-track {
  background-color: #fff;
}
</style>
